package com.yxmadoc.umlproject.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yxmadoc.umlproject.model.Customer;
import com.yxmadoc.umlproject.model.Repairer;
import com.yxmadoc.umlproject.repository.CustomerRepository;
import com.yxmadoc.umlproject.repository.RepairerRepository;
import com.yxmadoc.umlproject.service.CustomerService;
import com.yxmadoc.umlproject.service.LoginService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private RepairerRepository repairerRepository;

    @Override
    public boolean login(Customer customer) {
        Customer customerInDB = customerRepository.findByCustomerPhone(customer.getCustomerPhone());
        if(customerInDB != null){
            if(customerInDB.getCustomerPassword().equals(DigestUtils.md5Hex(customer.getCustomerPassword()))){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean login(Repairer repairer) {
        Repairer repairerInDB = repairerRepository.findByRepairerPhone(repairer.getRepairerPhone());
        if(repairerInDB != null){
            if(repairerInDB.getRepairerPassword().equals(DigestUtils.md5Hex(repairer.getRepairerPassword()))){
                return true;
            }
        }
        return false;
    }

    @Override
    public String getToken(Customer customer) {
        String token = "";
        try{
            token = JWT.create().withAudience(customer.getCustomerId()).sign(Algorithm.HMAC256(customer.getCustomerPassword()));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return token;
    }

    @Override
    public String getToken(Repairer repairer) {
        String token = "";
        try{
            token = JWT.create().withAudience(repairer.getRepairerId()).sign(Algorithm.HMAC256(repairer.getRepairerPassword()));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return token;
    }
}
